package cn.sdhuijin.healthexam.ui.popup;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import cn.sdhuijin.healthexam.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * 日期选择弹出框
 * 
 * @author houyuchun
 * 
 */
public class DateTimePickerDialog implements OnDateChangedListener {
	private DatePicker datePicker;
	private AlertDialog alertDialog;
	private String dateTime;
	private Activity activity;

	public DateTimePickerDialog(Activity activity) {
		this.activity = activity;
	}

	public void init(DatePicker datePicker) {
		Calendar calendar = Calendar.getInstance();
		datePicker.init(calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), this);
	}

	public AlertDialog dateTimePicKDialog(final EditText editText, int type) {
		switch (type) {
		case 1:
			LinearLayout datePickerLayout = (LinearLayout) activity
					.getLayoutInflater().inflate(R.layout.activity_date_picker,
							null);
			datePicker = (DatePicker) datePickerLayout
					.findViewById(R.id.datepicker);
			init(datePicker);
			alertDialog = new AlertDialog.Builder(activity)
					.setTitle("日期设置：")
					.setView(datePickerLayout)
					.setPositiveButton("设置",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									editText.setText(dateTime);
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									editText.setText("");
								}
							}).show();
			onDateChanged(null, 0, 0, 0);
			return alertDialog;
		default:
			return null;
		}
	}

	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(datePicker.getYear(), datePicker.getMonth(),
				datePicker.getDayOfMonth());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		dateTime = sdf.format(calendar.getTime());
	}
}
